package org.rcy.framework.thrift.metadata;

import org.rcy.framework.thrift.ReflectionUtils;

import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public enum JavaType {
	BASIC, DATE, ENUM, LIST, SET, MAP, EXCEPTION, STRUCT, BINARY;

	private static Map<Class<?>, JavaType> typeMap = new HashMap();

	static {
		typeMap.put(boolean.class, BASIC);
		typeMap.put(Boolean.class, BASIC);
		typeMap.put(Byte.class, BASIC);
		typeMap.put(byte.class, BASIC);
		typeMap.put(double.class, BASIC);
		typeMap.put(Double.class, BASIC);
		typeMap.put(short.class, BASIC);
		typeMap.put(Short.class, BASIC);
		typeMap.put(int.class, BASIC);
		typeMap.put(Integer.class, BASIC);
		typeMap.put(long.class, BASIC);
		typeMap.put(Long.class, BASIC);
		typeMap.put(String.class, BASIC);
		typeMap.put(Date.class, DATE);
		typeMap.put(Enum.class, ENUM);
		typeMap.put(List.class, LIST);
		typeMap.put(Set.class, SET);
		typeMap.put(Map.class, MAP);
		typeMap.put(ByteBuffer.class, BINARY);
		typeMap.put(ExceptionData.class, EXCEPTION);
	}

	public static JavaType determine(Type original) {
		Class<?> type = ReflectionUtils.resolveType(original);

		JavaType javaType = typeMap.get(type);
		if (javaType != null) {
			return javaType;
		}

		if (Date.class.isAssignableFrom(type)) {
			return DATE;
		}

		if (Enum.class.isAssignableFrom(type)) {
			return ENUM;
		}

		if (List.class.isAssignableFrom(type)) {
			return LIST;
		}

		if (Set.class.isAssignableFrom(type)) {
			return SET;
		}

		if (Map.class.isAssignableFrom(type)) {
			return MAP;
		}
		// 以上类型都不匹配则返回STRUCT类型
		return STRUCT;
	}

}